extends Node2D

class_name WaterNode

var circle
var circle2
var speed: Vector2 = Vector2.ZERO
var force: Vector2 = Vector2.ZERO
var mass = 10
var drag_k = 10
var force_strength = 40000
var water_sampling_dist = 3
var water_force_k = 20000
var max_speed = 200.0
var gravity = 3000

onready var MAIN = find_parent("MAIN")



func _process(delta):
	circle2.position = position
	integrate_forces(delta)
	circle.color.g = (max_speed + speed.x) / 2 / max_speed
	circle.color.b = (max_speed + speed.y) / 2 / max_speed
	#print (circle.color.g," ", speed.x)
	position += speed*delta
	speed += force*delta/mass
	if position.x < 0 or position.x>1023:
		position.x = clamp(position.x, 0, 1023)
		speed.x = -speed.x
	if position.y < 0 or position.y>539:
		position.y = clamp(position.y, 0, 539)
		speed.y = -speed.y
	

func integrate_forces(delta):
	force = Vector2.ZERO
	var vector_to_mouse = (get_viewport().get_mouse_position() - position)
	var distance_from_mouse = vector_to_mouse.length()
	
	if distance_from_mouse > 10 and Input.is_mouse_button_pressed(1):
		force += vector_to_mouse.normalized() * (force_strength / sqrt(distance_from_mouse))
	var drag = -speed * drag_k
	force += drag
	force += Vector2(0,1) * gravity 
	#var viscous = (get_speed_here()-speed) * get_viscosity_here() 
	#force += viscous
	var water = get_water_force()
	force += water
	#print(water.length()/force.length())
	
	pass

func get_viscosity_here():
	var field = MAIN.field_at_vector(position).x
	var viscosity = 0
	if field >=1.0:
		viscosity = (field - 0.6)/(1-0.6)*100
	return viscosity
	
func get_speed_here():
	var s = Vector2.ZERO
	var f = MAIN.field_at_vector(position)
	s = Vector2(
		f.x,
		f.z
		)
	s *= max_speed
	s -= Vector2.ONE*max_speed
	return s
	
	
func potential_at_pixel(vec2):
	var coords = Vector2(floor(vec2.x),floor(vec2.y))
	var potential = MAIN.field_at_vector(coords).x
	#print (potential, coords)
	return  MAIN.potential_curve.interpolate( potential)

func get_water_force():
	var upper_pixel = position + Vector2(0,water_sampling_dist)
	var lower_pixel = position + Vector2(0,-water_sampling_dist)
	var right_pixel = position + Vector2(water_sampling_dist,0)
	var left_pixel = position + Vector2(-water_sampling_dist,0)
	#var potential_here = potential_at_pixel(position)
	
	var f = Vector2(
		potential_at_pixel(right_pixel) - potential_at_pixel(left_pixel),
		potential_at_pixel(upper_pixel) - potential_at_pixel(lower_pixel)
	)
	f *= -1*water_force_k
	#print(f)
	return f

# Declare member variables here. Examples:
# var a = 2
# var b = "text"


# Called when the node enters the scene tree for the first time.
func _ready():
	circle = Circle.new(5)
	circle2 = Circle.new(5)
	circle2.z_index = 5
	call_deferred("add_child", circle)
	MAIN.call_deferred("add_child", circle2)
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#	pass
